// @ts-ignore
import passport from '@/assets/passport.png';
// @ts-ignore
import traffic from '@/assets/traffic.png';
// @ts-ignore
import station from '@/assets/station.png';
// @ts-ignore
import orgin from '@/assets/origin.png';
// @ts-ignore
import end from '@/assets/end.png';

const icon = {
    orgin:{
        url: orgin,
        size: [25,40]
    },
    end:{
        url: end,
        size: [25,40] 
    },
    passport:{
        url: passport,
        size: [24,24]
    },
    trafficSignal:{
        url: traffic,
        size: [22,10]
    },
    stop:{
        url: station,
        size: [32,32]
    }
}

function AMarker(position:any, icon:any, title:any){
    let x = icon.size[0];
    let y = icon.size[1];
    return  new AMap.Marker({
        position: position,
        title: title,
        icon: new AMap.Icon({
            image: icon.url,
            size:new AMap.Size(x,y),
            imageSize:new AMap.Size(x,y),
        }),
        offset: new AMap.Pixel(-0.5*x, -1*y)
    })
}
function AInfowindow(map:any, position:any, content:any, icon:any){
    let y = icon.size[1]
    map.setCenter(position);
    let infoWindow = new AMap.InfoWindow({
        content:content,
        offset:new AMap.Pixel(0,-1*y)
    })
    infoWindow.open(map,position)
}
function APolyline(path:any,color:any){
    let line = new AMap.Polyline({
        path: path,
        strokeWeight: 3,
        strokeColor: color,
        lineJoin: 'round',
        cursor:"pointer"
    })
    return line;
}
function ARoad(data:any, color:any){
    let road:any = [];
    let coordList:any = [];
    data.split(',').map((list: any) =>{
        let path:any = [];
        list.split('|').map((sub: any) => {
            path.push(sub.split(';'))
        })
        coordList.push(path)
    })
    coordList.map((item:any)=>{
        let line = APolyline(item,color);
        road.push(line);
    })
    return road;
}
function APolygon(data:any, color:any, style:any){
    let path:any = [];
    data.split(';').map((sub:any)=>{
        path.push(sub.split(','))
    })
    return new AMap.Polygon({
        path: path,
        strokeColor: "#F45B5B", 
        strokeWeight: 0,
        strokeOpacity: 0.8,
        fillColor: color,
        fillOpacity: 0.3,
        strokeStyle: style,
        cursor:"pointer"
    })
}
function driving(map:any,path:any,color:any,lineName:string){
    return new Promise((reslove)=>{
        map.plugin('AMap.Driving',() => {
            // @ts-ignore
            let route = new AMap.Driving({
                // @ts-ignore
                policy: AMap.DrivingPolicy.LEAST_TIME,
                showTraffic: false,
                hideMarkers:true,
            })
            route.search(path.shift(),path.pop(),{waypoints:path},(status:any,result:any)=>{
                if(status === 'complete'){
                    let busRouteArr:any = []
                    result.routes[0].steps.map((item:any)=>{
                        busRouteArr = busRouteArr.concat(item.path);
                    })
                    let line = APolyline(busRouteArr,color);
                    line.on("click",(e)=>{
                        let infoWindow = new AMap.InfoWindow({
                            content: lineName,
                        })
                        map.getAllOverlays('polyline').map((item:any)=>{
                            item.setOptions({showDir:false,strokeWeight:3,zIndex:10})
                        })
                        e.target.setOptions({showDir:true,strokeWeight:6,zIndex:20})
                        infoWindow.open(map,e.lnglat)
                    })
                    reslove(line)
                }
            })
        })
    })
}
// function transfer(map,path,color){
//     map.plugin('AMap.Driving',() => {
//         // @ts-ignore
//         let route = new AMap.Driving({
//             // @ts-ignore
//             policy: AMap.DrivingPolicy.LEAST_TIME,
//             showTraffic: false,
//             hideMarkers:true,
//         })
//         route.search(path.shift(),path.pop(),{waypoints:path},(status:any,result:any)=>{
//             if(status === 'complete'){
//                 let busRouteArr:any = []
//                 result.routes[0].steps.map((item:any)=>{
//                     busRouteArr = busRouteArr.concat(item.path);
//                 })
//                 let line = APolyline(busRouteArr,color);
//                 map.add(line)
//             }
//         })
//     })
// }

export function drawRoads(map: any,data: any){
    if(data instanceof Array){
        map.clearMap();
        let arr:any = [];
        data.forEach((item: any) => {
            let color: string = '';
            if(item.coordList){
                switch(item.roadLevel){
                    case '主干道':
                        color = "orange";
                        break;
                    case '次干道':
                        color = 'red';
                        break;
                    case '支路':
                        color = 'blue';
                        break;
                    default:
                        color = 'yellow';
                        break;
                }
                arr = arr.concat(ARoad(item.coordList,color))
            }
        });
        map.add(arr);
        map.setFitView();
    }else{
        map.remove(map.getAllOverlays('marker'))
        let checkRoad = map.getAllOverlays('polyline').filter((_:any)=>{
            return (_.B.strokeColor == '#0091ff')
        })
        map.remove(checkRoad)
        
        let roadArr:any = [];
        if(data.coordList){
            let road = ARoad(data.coordList,'#0091ff')
            roadArr = roadArr.concat(road)
        }
        
        if(data.roadStartLongitude){
            let startPosition = data.roadStartCoord.split(';');
            let startMarker = AMarker(startPosition, icon.orgin,'');
            let endPosition = data.roadEndCoord.split(';');
            let endMarker = AMarker(endPosition,icon.end,'');
            roadArr = roadArr.concat(startMarker,endMarker)
        }
        
        if(data.trafficLightList[0] != undefined){
            data.trafficLightList.forEach((item:any)=>{
                let position = [item.lng, item.lat]
                let signal = AMarker(position,icon.trafficSignal,'')
                roadArr = roadArr.concat(signal)
            })
        }

        if(data.checkPointList[0] != undefined){
            data.checkPointList.forEach((item:any)=>{
                let position = [item.lng, item.lat]
                let passport = AMarker(position,icon.passport,'')
                roadArr = roadArr.concat(passport)
            })
        }

        map.add(roadArr);
        map.setFitView(roadArr);
    }
}

export function drawBuildings(map:any,data:any){
    if(data.length > 1){
        map.clearMap();
        let arr:any = [];
        data.map((item:any)=>{
            let build = APolygon(item.longitudeList, 'skyblue', 'soild')
            build.on('click',(e)=>{
                AInfowindow(map,e.lnglat,item.buildName,icon.trafficSignal)
            })
            arr.push(build);
        })
        map.add(arr);
        map.setFitView();
    }else{
        map.remove(map.getAllOverlays('polyline'))
        let checkBuild = map.getAllOverlays('polygon').filter((_:any)=>{
            return (_.B.strokeStyle === 'dashed')
        })
        map.remove(checkBuild)

        let buildRoad:any = [];
        let build = APolygon(data[0].longitudeList, '', 'dashed')
        build.setOptions({strokeWeight:4,strokeColor: "red",})
        build.on('click',(e)=>{
            AInfowindow(map,e.lnglat,data[0].buildName,icon.trafficSignal)
        })
        buildRoad.push(build)
        if(data[0].roadList){
            data[0].roadList.forEach((item:any)=>{
                if(item.coordList.length){
                    buildRoad = buildRoad.concat(ARoad(item.coordList,'#0091ff'))
                }
            })
        }
        map.add(buildRoad);
        map.setFitView(build);
    }
}

export function drawPassports(map: any, data: any){
    if(data instanceof Array){
        map.clearMap();
        let arr:any = [];
        data.forEach((item: any) => {
            let position = [item.lng, item.lat];
            let marker = AMarker(position,icon.passport,item.deviceName)
            arr.push(marker);
        });
        let markerLayer = new AMap.OverlayGroup(arr);
        markerLayer.on("click",(e:any)=>{
            let position = e.target.getPosition();
            let content = e.target.getTitle();
            AInfowindow(map,position,content,icon.passport)
        })
        map.add(markerLayer);
        map.setFitView();
    }else{
        let position = [data.lng, data.lat];
        let content = data.deviceName
        AInfowindow(map,position,content,icon.passport)
        map.remove(map.getAllOverlays('polyline'))
        if(data.coordList){
            let road = ARoad(data.coordList,'#0091ff')
            map.add(road)
        }
        map.setZoom(17);
    }
}

export function drawTrafficSignals(map: any, data: any){
    if(data instanceof Array){
        map.clearMap();
        let arr:any = [];
        data.forEach((item: any) => {
            let position = [item.lng,item.lat]
            let marker = AMarker(position,icon.trafficSignal,item.deviceName)
            arr.push(marker);
        });
        let markerLayer = new AMap.OverlayGroup(arr);
        markerLayer.on("click",(e:any)=>{
            let position = e.target.getPosition();
            let content = e.target.getTitle();
            AInfowindow(map,position,content,icon.trafficSignal)
        })
        map.add(markerLayer);
        map.setFitView();
    }else{
        let position = [data.lng, data.lat];
        let content = data.deviceName
        AInfowindow(map,position,content,icon.trafficSignal)
        map.remove(map.getAllOverlays('polyline'))
        if(data.coordList){
            let road = ARoad(data.coordList,'#0091ff')
            map.add(road)
        }
        map.setZoom(17);
    }
}

export function drawBusRoutes(map: any, data: any){
    if(data instanceof Array){
        map.clearMap();
        data.forEach((item:any)=>{
            let siteArr:any = [];
            item.busContact.forEach((sub:any)=>{
                if(sub.longitude && sub.latitude){
                    siteArr.push([sub.longitude, sub.latitude]);
                }
            })
            if(siteArr.length > 1){
                let color = '#'+Math.floor(Math.random()*0xffffff).toString(16);
                driving(map,siteArr,color,item.lineName).then((res)=>{
                    map.add(res)
                })
            }
        })
        map.setZoomAndCenter(13,[113.870836, 23.109164])
    }else{
        map.remove(map.getAllOverlays('marker'))
        let removeBusRoute = map.getAllOverlays('polyline').filter((_:any)=>{
            return (_.B.strokeColor === '#0091ff')
        })
        map.remove(removeBusRoute)
        let arr:any = [];
        let markerArr:any = [];
        data.busContact.forEach((item:any)=>{
            if(item.longitude && item.latitude){
                arr.push([item.longitude,item.latitude])
                let position = [item.longitude,item.latitude];
                let marker = AMarker(position, icon.stop, item.siteName);
                markerArr.push(marker)
            }
        })
        let markerLayer = new AMap.OverlayGroup(markerArr);
        markerLayer.on("click",(e:any)=>{
            let position = e.target.getPosition();
            let content = e.target.getTitle();
            AInfowindow(map,position,content,icon.stop)
        })
        map.add(markerLayer);
        map.setFitView(markerArr);
        driving(map,arr,'#0091ff',data.lineName).then((checkBusroute)=>{
            map.getAllOverlays('polyline').map((item:any)=>{
                item.setOptions({showDir:false,strokeWeight:3})
            })
            // @ts-ignore
            checkBusroute.setOptions({showDir:true,strokeWeight:6})
            map.add(checkBusroute)
        })
    }
}

export function drawBusStations(map: any, data: any){
    if(data instanceof Array){
        map.clearMap();
        let arr: any = [];
        data.forEach((item: any) => {
            let position = [item.longitude,item.latitude]
            let marker = AMarker(position, icon.stop, item.siteName)
            arr.push(marker)
        });
        let markerLayer = new AMap.OverlayGroup(arr);
        markerLayer.on("click",(e:any)=>{
            let position = e.target.getPosition();
            let content = e.target.getTitle();
            AInfowindow(map,position,content,icon.stop)
        })
        map.add(markerLayer);
        map.setFitView();
    }else{
        let position = [data.longitude, data.latitude];
        let content = data.siteName
        AInfowindow(map,position,content,icon.passport);
    }
}

export function stationToRoutes(map:any, data:any){
    map.remove(map.getAllOverlays('polyline'))
    data.forEach(async(item:any)=>{
        let siteArr:any = [];
        item.busContact.forEach((sub:any)=>{
            if(sub.longitude && sub.latitude){
                siteArr.push([sub.longitude, sub.latitude]);
            }
        })
        if(siteArr.length > 1){
            driving(map,siteArr,'#0091ff',item.lineName).then((route)=>{
                map.add(route)
            })
        }
    })
    map.setFitView();
}

export function passportMarker(map:any,data:any){
    let position = [data.lng, data.lat];
    let title = data.deviceName;
    let marker = AMarker(position,icon.passport,title)
    marker.on('click',(e)=>{
        let infoWindow = new AMap.InfoWindow({
            content:e.target.getTitle(),
            offset:new AMap.Pixel(0,-24)
        })
        infoWindow.open(map,e.target.getPosition())
    })
    map.add(marker)
}

export function stopMarker(map:any,data:any){
    let stopArr:any = []
    data.forEach((item:any)=>{
        let position = [item.longitude,item.latitude]
        let marker = AMarker(position,icon.stop,item.siteName)
        marker.on('click',(e)=>{
            let infoWindow = new AMap.InfoWindow({
                content:e.target.getTitle(),
                offset:new AMap.Pixel(0,-32)
            })
            infoWindow.open(map,e.target.getPosition())
        })
        stopArr.push(marker)
    })
    map.add(stopArr);
}